package com.cloud.shopping.page.feign.service.impl;

import com.cloud.shopping.page.feign.service.SeckillPageService;
import com.cloud.shopping.seckill.feign.SeckillGoodsFeign;
import com.cloud.shopping.seckill.model.SeckillGoods;
import com.cloud.shopping.tool.RespResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import java.io.File;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author John.zhang
 * @version Id: SeckillPageServiceImpl, v 1.0 2021/1/8 11:48 ZhiYong Exp $
 */

@Service
public class SeckillPageServiceImpl implements SeckillPageService {

    @Resource
    private SeckillGoodsFeign seckillGoodsFeign;

    @Resource
    private TemplateEngine templateEngine;

    @Value("${pagePath}")
    private String pagePath;


    @Override
    public void html(String id) throws Exception {
        //1、创建容器对象(上下文对象)
        Context context = new Context();
        //2、设置模板数据  loadSeckillData(id)-》Map
        context.setVariables(loadSeckillData(id));
        //3、指定文件生成后存储路径
        File file = new File(pagePath, id + ".html");
        PrintWriter writer = new PrintWriter(file, "UTF-8");
        //4、执行合成生成
        templateEngine.process("seckill_item", context, writer);
    }

    /**
     *删除过期的秒杀商品详情
    * @param id id
     */
    @Override
    public void delete(String id) {
        //创建要删除的文件对象
        File file = new File(pagePath, id + ".html");
        if (file.exists()) {
            file.delete();
        }
    }

    /**
     * 加载秒杀数据
     * @param id id
     * @return Map
     */
    private Map<String, Object> loadSeckillData(String id) {
        RespResult<SeckillGoods> goodsResp = seckillGoodsFeign.one(id);
        //将商品信息存入到Map中
        if (goodsResp.getData() != null) {
            Map<String, Object> dataMap = new HashMap<>(16);
            dataMap.put("item", goodsResp.getData());
            return dataMap;
        }
        return null;
    }
}
